package com.heima.redisson.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/lock")
public class RedissionController {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 可重入锁
     * @return
     */
    @GetMapping("/reentrant")
    public String reentrantLock(){
        RLock lock = redissonClient.getFairLock("fail_lock");
        Boolean isLock=false;
        try {
            //尝试获取锁，--获取锁失败之后会阻塞一段时间,直到获取锁
            //isLock = lock.tryLock();
            isLock=lock.tryLock(10,30, TimeUnit.SECONDS);

            if(isLock){
                log.info("线程{},开始执行业务逻辑--------",Thread.currentThread().getName());
                Thread.sleep(2000);
                return "SUCESS";
            }else {
                return "Fail!获取锁失败";
            }
        } catch (InterruptedException e) {
            log.info("线程：{},业务执行出现异常",Thread.currentThread().getName());
            return "Fail,程序异常";
        }finally {
            if(isLock){
                lock.unlock();
                log.info("线程：{},释放锁",Thread.currentThread().getName());
            }
        }


    }
}
